package com.pudding.task;

import cn.hutool.core.bean.BeanUtil;
import com.pudding.entity.po.TbExcel;
import com.pudding.entity.vo.ExcelVO;
import com.pudding.mapper.ExcelMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @Author Pudding
 * @Date 2025/3/27 11:55
 */
@Slf4j
@Component
@NoArgsConstructor
public class DeadMainThread implements Runnable {

    private int startPosition; //当前线程需要处理的总数据中的开始位置
    private int endPosition; //当前线程需要处理的，总数据中的结束位置
    private List<ExcelVO> list = Collections.synchronizedList(new ArrayList<>()); //需要处理的拆分之前的全部数据
    private CountDownLatch count; //线程计数器
    private ExcelMapper excelMapper; //数据库操作对象

    public DeadMainThread(CountDownLatch count, ExcelMapper excelMapper, List<ExcelVO> list, int startPosition, int endPosition) {
        this.startPosition = startPosition;
        this.endPosition = endPosition;
        this.excelMapper = excelMapper;
        this.list = list;
        this.count = count;
    }

    @Override
    public void run() {
        try {
            // 获取当前线程需要处理的数据 → 拆分后的数据
            List<ExcelVO> newList = list.subList(startPosition, endPosition);
            // 批量新增
            excelMapper.insertBatch(BeanUtil.copyToList(newList, TbExcel.class));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //当一个线程执行完了计数要减一不然这个线程会被一直挂起
            count.countDown();
            log.info("减一===》{}", count.getCount());
        }
    }
}
